package com.lxs;

import org.eclipse.jetty.proxy.ProxyServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class JettyProxyServer {

    // 路由配置：路径前缀 -> 目标服务
    private static final Map<String, String> ROUTE_MAPPING = new HashMap<>();

    static {
        ROUTE_MAPPING.put("/a", "http://localhost:9001");  // /a/* 转发到 9001
        ROUTE_MAPPING.put("/b", "http://localhost:9002");  // /b/* 转发到 9002
    }

    public static void main(String[] args) throws Exception {
        int proxyPort = 8080;
        Server server = new Server(proxyPort);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        // 为每个路由创建代理 Servlet
        for (Map.Entry<String, String> route : ROUTE_MAPPING.entrySet()) {
            String pathPrefix = route.getKey();
            String targetUrl = route.getValue();

            ServletHolder proxyServlet = new ServletHolder(createProxyServlet(pathPrefix, targetUrl));
            context.addServlet(proxyServlet, pathPrefix + "/*");

            System.out.println("注册路由: " + pathPrefix + "/* -> " + targetUrl);
        }

        // 添加健康检查
        context.addServlet(HealthServlet.class, "/health");

        server.setHandler(context);
        server.start();

        System.out.println("Jetty Proxy Server started on port " + proxyPort);
        System.out.println("路由配置: " + ROUTE_MAPPING);

        server.join();
    }

    private static ProxyServlet createProxyServlet(final String pathPrefix, final String targetUrl) {
        return new ProxyServlet.Transparent() {
            @Override
            protected String rewriteTarget(HttpServletRequest request) {
                String path = request.getRequestURI();
                String query = request.getQueryString();

                // 移除路径前缀（例如：/a/demo/hello -> /demo/hello）
                String targetPath = path.substring(pathPrefix.length());

                // 构建目标URL
                StringBuilder newTarget = new StringBuilder(targetUrl);
                newTarget.append(targetPath);

                if (query != null) {
                    newTarget.append('?').append(query);
                }

                System.out.println("代理请求: " + path + " -> " + newTarget.toString());
                return newTarget.toString();
            }
        };
    }

    // 健康检查 Servlet
    public static class HealthServlet extends javax.servlet.http.HttpServlet {
        @Override
        protected void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)
                throws javax.servlet.ServletException, java.io.IOException {
            resp.setContentType("application/json");
            resp.setStatus(200);
            resp.getWriter().println("{\"status\": \"ok\", \"service\": \"jetty-proxy\"}");
        }
    }
}
